package com.peng.contentproviderdemo;

import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        queryContentProvider();

        //构建数据插入数据库
        Uri uri = Uri.parse("content://com.peng.contentproviderdemo.BookContentProvider/book");
        ContentValues contentValues = new ContentValues();
        contentValues.put("_id", 6);
        contentValues.put("name", "程序设计的艺术");
        getContentResolver().insert(uri, contentValues);

        Cursor bookCursor = getContentResolver().query(uri, new String[]{"_id", "name"}, null, null, null);
        while (bookCursor.moveToNext()) {
            Book book = new Book();
            book.id = bookCursor.getInt(0);
            book.name = bookCursor.getString(1);
            Log.d(TAG, "onCreate: query book:" + book.toString());
        }
        //cursor光标使用完之后，立即关闭
        bookCursor.close();

        Uri userUri = Uri.parse("content://com.peng.contentproviderdemo.BookContentProvider/user");
        Cursor userCursor = getContentResolver().query(userUri, new String[]{"_id", "name", "sex"}, null, null, null);
        while (userCursor.moveToNext()) {
            User user = new User();
            user.id = userCursor.getInt(0);
            user.name = userCursor.getString(1);
            user.sex = userCursor.getInt(2);
            Log.d(TAG, "onCreate: query book:" + user.toString());
        }
        bookCursor.close();
    }

    /**
     * 访问ContentProvider
     */
    public void queryContentProvider() {
        //下面的Uri字符串就是authorities指定的值
        Uri uri = Uri.parse("content://com.peng.contentproviderdemo.BookContentProvider");
//        getContentResolver().query(uri, null, null, null, null);
//        getContentResolver().query(uri, null, null, null, null);
//        getContentResolver().query(uri, null, null, null, null);
    }

}
